package cn.com.xf.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.xf.common.AbstractBaseController;
import cn.com.xf.common.Constants;
import cn.com.xf.common.StringUtil;
import cn.com.xf.domain.TblApiBar;
import cn.com.xf.domain.TsSiteinfo;
import cn.com.xf.service.TblApiBarService;
import cn.com.xf.utils.ExcelUtils;
import cn.com.xf.utils.encode.EncrypTool;
import cn.com.xf.web.PageModel;
import cn.com.xf.web.XFMappingJacksonJsonView;
import cn.com.xf.web.form.BarForm;

@Controller
@RequestMapping("/bar")
public class BarController extends AbstractBaseController {

	@Autowired
	private TblApiBarService tbBarService;
	
	@RequestMapping
	public ModelAndView index(HttpServletRequest request,
			HttpServletResponse response, BarForm form) throws Exception {
		form.setTab("bar");
		ModelAndView mv = new ModelAndView("/bar/index", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}

	@RequestMapping(value = "/add")
	public ModelAndView add(HttpServletRequest request,
			HttpServletResponse response, BarForm form) throws Exception {
		ModelAndView mv = new ModelAndView("/bar/add", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}

	@RequestMapping(value = "/batchAdd")
	public ModelAndView batchAdd(HttpServletRequest request,
			HttpServletResponse response, BarForm form) throws Exception {
		ModelAndView mv = new ModelAndView("/bar/batchAdd", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}
	
	@RequestMapping(value = "/doBatchAdd")
	public ModelAndView doBatchAdd(HttpServletRequest request, HttpServletResponse response, BarForm form) {
		ModelAndView mv = new ModelAndView("/bar/add_result", Constants.FORM_COMMAND_KEY, form); 
		List<List<Map<String, String>>> list =null;
		try {
			list = ExcelUtils.readExcelWithTitle(form.getExcelFile());
		} catch (Exception e) {
			mv.addObject("status","FAILD");
			mv.addObject("msg",e.getMessage());
			return mv;
		}
		List<TblApiBar> barList = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			List<Map<String,String>> listMap = list.get(i);
			for (Map<String,String> map: listMap) {
				String deviceId = map.get("DEVICEID");
				String siteId = map.get("SITEID");
				String brand = map.get("BRAND");
				if (deviceId == null || siteId == null || brand == null) {
					mv.addObject("status","FAILD");
					mv.addObject("msg","excel格式不正确");
					return mv;
				}
				TblApiBar tbbar = new TblApiBar();
				tbbar.setDeviceid(deviceId);
				tbbar.setSiteid(siteId);
				tbbar.setCompanyName(brand);
				tbbar.setAddUser(form.getAddUser());
				tbbar.setAddTime(new Date());
				tbbar.setAddTimeStr(DateFormatUtils.format(tbbar.getAddTime(), "yyyy-MM-dd HH:mm:ss"));
				barList.add(tbbar);
			}
		}
		tbBarService.insertBatchBar(barList);
		mv.addObject("status","SUCCESS");
		return mv;
	}
	
	@RequestMapping(value = "/doAdd")
	public ModelAndView doAdd(HttpServletRequest request, HttpServletResponse response, @Valid BarForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/bar/add_result", Constants.FORM_COMMAND_KEY, form); 
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		TblApiBar tbbar = tbBarService.selectByDeviceID(form.getDeviceid());
		if(tbbar!=null){
			mv.addObject("status","FAILD");
			mv.addObject("msg","");
			return mv;
		}
		tbBarService.insertTbBar(form);
		mv.addObject("status","SUCCESS");
		return mv;
	}
	
	@RequestMapping(value = "/manageList")
	public ModelAndView manageList(HttpServletRequest requets, HttpServletResponse response, BarForm form) throws Exception{
		ModelAndView mv = new ModelAndView("/bar/manage_bar",Constants.FORM_COMMAND_KEY,form);
		String siteid = StringUtil.StringFilter(form.getSiteid());
		String brand = StringUtil.StringFilter(form.getBrand());
		String deviceid = StringUtil.StringFilter(form.getDeviceid());
		form.setSiteid(siteid);
		form.setBrand(brand);
		form.setDeviceid(deviceid);
		int count = tbBarService.selectCount(siteid,brand,deviceid);
		if(count == 0){
			return mv;
		}
		
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();
		
		String orderByField = "ADD_TIME";
		String orderByMode = "DESC";
		if (StringUtils.isNotBlank(form.getOrderByField()) && StringUtils.isNotBlank(form.getOrderByMode())) {
			if ("deviceid".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "DEVICEID";
			}
			if ("siteid".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "SITEID";
			}
			if ("brand".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "COMPANY_NAME";
			}
			if ("addTime".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "ADD_TIME";
			}
			if ("asc".equalsIgnoreCase(form.getOrderByMode()) || "desc".equalsIgnoreCase(form.getOrderByMode())) {
				orderByMode = form.getOrderByMode();
			}
		}
		
		List<TblApiBar> list = tbBarService.select(begin, pageSize, orderByField, orderByMode,siteid,brand,deviceid);
		mv.addObject("list",list);
		return mv;
	}
	
	@RequestMapping(value = "/doDelete")
	public ModelAndView doDelete(HttpServletRequest request, HttpServletResponse response, BarForm form) throws Exception{
		String idStr = form.getId();
		String realId = "";
		if(StringUtils.isNotBlank(idStr)){
			realId = EncrypTool.dencode(idStr);
		}
		int result = tbBarService.delete(realId);
		Map map = new HashMap<String, String>();
		if (result < 0) {
			map.put("status", "FAILD");
		} else if (result >= 0) {
			map.put("status", "SUCCESS");
		}
		ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
		return mv;
	}
	
	
	@RequestMapping(value = "/getSites")
	@ResponseBody
	public List<TsSiteinfo> getSites(HttpServletRequest request, HttpServletResponse response, BarForm form) throws Exception{
		List<TsSiteinfo> list = tbBarService.selectSites();
		return list;
	}
	
	@RequestMapping("/sites")
	@ResponseBody
	public List<Map<String, Object>> getSites(@RequestParam("term") String term) {
		term = term.trim().toUpperCase();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		List<TsSiteinfo> sites = tbBarService.selectSites(term);
		for (TsSiteinfo site: sites) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", site.getSiteid());
			map.put("text", site.getSitename());
			list.add(map);
		}
		Map<String, Object> humenCarlineMap = new HashMap<String, Object>();
		humenCarlineMap.put("id", "HUMEN");
		humenCarlineMap.put("text", "虎门仓车线");
		list.add(humenCarlineMap);
		Map<String, Object> shenzhenCarlineMap = new HashMap<String, Object>();
		shenzhenCarlineMap.put("id", "SHENZHEN");
		shenzhenCarlineMap.put("text", "深圳仓车线");
		list.add(shenzhenCarlineMap);
		return list;
	}
}
